package com.avic.rong.questionOrAnswer.adapter.video;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.avic.rong.R;
import com.avic.rong.activity.VideoDetailActivity;
import com.avic.rong.questionOrAnswer.activity.PersonalHomeActivity;
import com.avic.rong.questionOrAnswer.api.CancelThumbApi;
import com.avic.rong.questionOrAnswer.api.CancelnCollectionApi;
import com.avic.rong.questionOrAnswer.api.CollectApi;
import com.avic.rong.questionOrAnswer.api.ThumbApi;
import com.avic.rong.questionOrAnswer.bean.VideoBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.GlideUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.TimeUtil;
import com.avic.rong.utils.ToastTools;
import com.bumptech.glide.Glide;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VideoAdapter extends RecyclerView.Adapter {

    private Context context;
    public List<VideoBean> mList;

    public VideoAdapter(Context context,List<VideoBean> mList) {
        this.context = context;
        this.mList = mList;
    }

   /* public void setmList(List<VideoBean> mList) {
        this.mList.addAll(mList);
        notifyDataSetChanged();
    }*/

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.item_collect_video, viewGroup, false);
        return new VideoNormalHolder(context,inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        VideoBean bean = mList.get(i);
        VideoNormalHolder videoNormalHolder = (VideoNormalHolder) viewHolder;
        videoNormalHolder.setRecyclerBaseAdapter(this);

        videoNormalHolder.onBind(i,bean.getSourceUrl());

        try {
            if (!TextUtils.isEmpty(bean.getPublicTime())){
                String time = TimeUtil.dateToStamp(bean.getPublicTime() + "");
                String data = stampToDate(Long.parseLong(time));
                videoNormalHolder.tv_date.setText(bean.getPublicTime() + "");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        videoNormalHolder.tvTitle.setText(bean.getTitle());
        if (!TextUtils.isEmpty(((PersonalHomeActivity)context).getNAME())){
            videoNormalHolder.tv_name.setText(((PersonalHomeActivity)context).getNAME());
        }
        if (!TextUtils.isEmpty(((PersonalHomeActivity)context).getAuthenticationInformation())) {
            videoNormalHolder.tv_position.setText(((PersonalHomeActivity)context).getAuthenticationInformation());
        }
        if (!TextUtils.isEmpty(((PersonalHomeActivity)context).getLOGO())){
            GlideUtils.loaderHanldeRoundImage(context,((PersonalHomeActivity)context).getLOGO(),videoNormalHolder.image_header,80);
        }else {
            Glide.with(context).load(R.mipmap.ic_default_head).into(videoNormalHolder.image_header);
        }

        if (!TextUtils.isEmpty(bean.getContImg())){
            GlideUtils.loaderRoundImage(context,bean.getContImg(),videoNormalHolder.imageView);
        }else {
            Glide.with(context).load(R.mipmap.ic_default_head).into(videoNormalHolder.imageView);
        }

        videoNormalHolder.tvLength.setText(bean.getDuraction());
        //评论数
        videoNormalHolder.tv_comment.setText(bean.getAppraiseNum()+"");
        //收藏数
        videoNormalHolder.tv_collect.setText(bean.getCollectNum()+"");
        //点赞数
        videoNormalHolder.tv_zan.setText(bean.getThumb()+"");

        //是否收藏
        if (bean.isIsFavorites()) {
            videoNormalHolder.cb_collect.setSelected(true);
        } else {
            videoNormalHolder.cb_collect.setSelected(false);
        }
        //是否点赞
        if (bean.isIsThumb()) {
            videoNormalHolder.cb_zan.setSelected(true);
        } else {
            videoNormalHolder.cb_zan.setSelected(false);
        }


        videoNormalHolder.cb_zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int contId = bean.getContId();
                if (videoNormalHolder.cb_zan.isSelected()) {
                    unZanReq(contId, context,videoNormalHolder);
                } else {
                    zanReq(contId, context,videoNormalHolder);
                }
            }
        });

        videoNormalHolder.cb_collect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int contId = bean.getContId();
                if (videoNormalHolder.cb_collect.isSelected()) {
                    unCollectReq(contId, context,videoNormalHolder);
                } else {
                    collectReq(contId, context,videoNormalHolder);
                }
            }
        });

        videoNormalHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(VideoDetailActivity.getIntent(context,bean.getContId()+""));
            }
        });

        videoNormalHolder.gsyVideoPlayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(VideoDetailActivity.getIntent(context,bean.getContId()+""));
            }
        });


    }

    private void unZanReq(int contId, Context context, VideoNormalHolder videoNormalHolder) {
        PersonalHomeActivity personalHomeActivity = (PersonalHomeActivity) context;
        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(SharedPreferencesUtil.getLoginToken())) {
            return;
        }

        map.put("contId", contId + "");

        //新闻1提问2回答3
        map.put("type", 1 + "");

        map.put("token", SharedPreferencesUtil.getLoginToken());
        final CancelThumbApi cancelThumbApi = new CancelThumbApi(personalHomeActivity, new SimpleOnNextListenerUnZan(videoNormalHolder));
        cancelThumbApi.setCache(false);
        cancelThumbApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(cancelThumbApi);


    }

    private void zanReq(int contId, Context context, VideoNormalHolder videoNormalHolder) {

        PersonalHomeActivity personalHomeActivity = (PersonalHomeActivity) context;
        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(SharedPreferencesUtil.getLoginToken())) {
            return;
        }

        map.put("contId", contId + "");
        //
        //新闻1提问2回答3
        map.put("type", 1 + "");
        map.put("token", SharedPreferencesUtil.getLoginToken());
        final ThumbApi thumbApi = new ThumbApi(personalHomeActivity, new SimpleOnNextListener(videoNormalHolder));
        thumbApi.setCache(false);
        thumbApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(thumbApi);


    }

    private void unCollectReq(int contId, Context context, VideoNormalHolder videoNormalHolder) {
        PersonalHomeActivity personalHomeActivity = (PersonalHomeActivity) context;
        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(SharedPreferencesUtil.getLoginToken())) {
            return;
        }

        map.put("targetId", contId + "");

        //收藏对象类型（1：软件服务  2：元器件 3：元器件审核备案 4：元器件试验检测  5：培训 6：标准 7：标准知识 8:企业 12:文章13:提问 14:回答）
        map.put("favoritesFlag", 12 + "");

        map.put("token", SharedPreferencesUtil.getLoginToken());
        final CancelnCollectionApi cancelnCollectionApi = new CancelnCollectionApi(personalHomeActivity, new SimpleOnNextListenerUnCollect(videoNormalHolder));
        cancelnCollectionApi.setCache(false);
        cancelnCollectionApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(cancelnCollectionApi);
    }

    private void collectReq(int contId, Context context, VideoNormalHolder videoNormalHolder) {
        PersonalHomeActivity personalHomeActivity = (PersonalHomeActivity) context;
        Map<String, String> map = new HashMap<>();

        if (contId <= 0 && TextUtils.isEmpty(SharedPreferencesUtil.getLoginToken())) {
            return;
        }
        map.put("targetId", contId + "");

        //收藏对象类型（1：软件服务  2：元器件 3：元器件审核备案 4：元器件试验检测  5：培训 6：标准 7：标准知识 8:企业 12:文章13:提问 14:回答）
        map.put("favoritesFlag", 12 + "");

        map.put("token",SharedPreferencesUtil.getLoginToken());
        final CollectApi collectApi = new CollectApi(personalHomeActivity, new SimpleOnNextListenerCollect(videoNormalHolder));
        collectApi.setCache(false);
        collectApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(collectApi);
    }

    //取消收藏
    public class SimpleOnNextListenerUnCollect extends HttpOnNextListener<BaseResultEntity> {
        VideoNormalHolder videoNormalHolder;

        public SimpleOnNextListenerUnCollect(VideoNormalHolder videoNormalHolder) {
            this.videoNormalHolder = videoNormalHolder;
        }
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                if (subjects.getCode().equals("1008")){
                    ToastTools.showToast(context, "取消收藏失败");
                }else {
                    ToastTools.showToast(context, subjects.getMsg());
                }

                return;
            }
            ToastTools.showToast(context, "取消收藏成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            videoNormalHolder.tv_collect.setText(num + "");
            videoNormalHolder.cb_collect.setSelected(false);
//            questionCollectNum();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //收藏
    public class SimpleOnNextListenerCollect extends HttpOnNextListener<BaseResultEntity>{
        VideoNormalHolder videoNormalHolder;

        public SimpleOnNextListenerCollect(VideoNormalHolder videoNormalHolder) {
            this.videoNormalHolder = videoNormalHolder;
        }

        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_1000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "收藏成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            videoNormalHolder.tv_collect.setText(num + "");
            videoNormalHolder.cb_collect.setSelected(true);
//            questionCollectNum();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    //点赞
    public class SimpleOnNextListener extends HttpOnNextListener<BaseResultEntity> {
        VideoNormalHolder videoNormalHolder;

        public SimpleOnNextListener(VideoNormalHolder videoNormalHolder) {
            this.videoNormalHolder = videoNormalHolder;
        }
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "点赞成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            videoNormalHolder.tv_zan.setText(num + "");
            videoNormalHolder.cb_zan.setSelected(true);
//            thumbNum();

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //取消点赞
    public class SimpleOnNextListenerUnZan extends HttpOnNextListener<BaseResultEntity> {
        VideoNormalHolder videoNormalHolder;

        public SimpleOnNextListenerUnZan(VideoNormalHolder videoNormalHolder) {
            this.videoNormalHolder = videoNormalHolder;
        }
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

            ToastTools.showToast(context, "取消点赞成功");
            Integer num = ((Double) subjects.getData()).intValue();
//            Integer num = Integer.parseInt(subjects.getData().toString());
            videoNormalHolder.tv_zan.setText(num + "");
            videoNormalHolder.cb_zan.setSelected(false);
//            thumbNum();
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(long timeMillis){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(timeMillis);
        return simpleDateFormat.format(date);
    }


    @Override
    public int getItemCount() {
        return mList.size();
    }
}
